<?php

use Service\Exception\ApiErrCode;

class ControllerAccountWishList extends Controller {

    const ROUTE = 'account/wishlist';

    /**
     * @throws Exception
     */
    public function index() {
		if (!$this->customer->isLogged()) {
			$this->session->data['redirect'] = $this->url->link(self::ROUTE);

			$this->response->redirect($this->url->link('account/login'));
		}

		$this->load->language(self::ROUTE);

		$this->load->model(self::ROUTE);

		$this->load->model('catalog/product');

		$this->load->model('tool/image');

		if (isset($this->request->get['remove'])) {
			// Remove Wishlist
			$this->model_account_wishlist->deleteWishlist($this->request->get['remove']);

			$this->session->data['success'] = $this->language->get('text_remove');

			$this->response->redirect($this->url->link(self::ROUTE));
		}

		$this->document->setTitle($this->language->get('heading_title'));

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_account'),
			'href' => $this->url->link('account/account')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link(self::ROUTE)
		);

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		$data['products'] = array();


        $limit = $this->request->get['limit'] ?? 35;
        $page = $this->request->get['page'] ?? 1;
        $start = ($page - 1) * $limit;

        $results = $this->modelAccountList()->getWishlist($start, $limit);
		foreach ($results as $result) {
			$product_info = $this->model_catalog_product->getProduct($result['product_id']);

			if ($product_info) {
				$image = $this->model_tool_image->resize($product_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_wishlist_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_wishlist_height'));

				if ($product_info['quantity'] <= 0) {
					$stock = $product_info['stock_status'];
				} elseif ($this->config->get('config_stock_display')) {
					$stock = $product_info['quantity'];
				} else {
					$stock = $this->language->get('text_instock');
				}

				if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
					$price = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
				} else {
					$price = false;
				}

				if ((float)$product_info['special']) {
					$special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
				} else {
					$special = false;
				}

				$data['products'][] = array(
					'product_id' => $product_info['product_id'],
					'thumb'      => $image,
					'name'       => $product_info['name'],
					'model'      => $product_info['model'],
					'stock'      => $stock,
					'price'      => $price,
					'special'    => $special,
					'href'       => $this->url->link('product/product', 'product_id=' . $product_info['product_id']),
					'remove'     => $this->url->link(self::ROUTE, 'remove=' . $product_info['product_id'])
				);
			} else {
				$this->model_account_wishlist->deleteWishlist($result['product_id']);
			}
		}

		$data['continue'] = $this->url->link('account/account');

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

        $pagination = new Pagination();
        $pagination->total = $this->modelAccountList()->getTotalWishlist();
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = $this->url->link(self::ROUTE, "page={page}&limit=$limit");
        $data['pagination'] = $pagination->render();

		$this->response->setOutput($this->load->view(self::ROUTE, $data));
	}

	public function add() {
		$this->load->language(self::ROUTE);

		$json = array();

		if (isset($this->request->post['product_id'])) {
			$product_id = $this->request->post['product_id'];
		} else {
			$product_id = 0;
		}

		$this->load->model('catalog/product');

		$product_info = $this->model_catalog_product->getProduct($product_id);

		if ($product_info) {
			if ($this->customer->isLogged()) {
				// Edit customers cart
				$this->load->model(self::ROUTE);

				$this->model_account_wishlist->addWishlist($this->request->post['product_id']);

				$wishlist_num = $this->model_account_wishlist->getTotalWishlist();
				$json['success'] = $this->language->get('text_success');
                $json['total_num'] = sprintf($wishlist_num);
				$json['total'] = sprintf($this->language->get('new_text_wishlist'), $wishlist_num);
			} else {
				if (!isset($this->session->data['wishlist'])) {
					$this->session->data['wishlist'] = array();
				}

				$this->session->data['wishlist'][] = $this->request->post['product_id'];

				$this->session->data['wishlist'] = array_unique($this->session->data['wishlist']);

                $json['total_num'] = sprintf(isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0);
				$json['success'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'), $this->url->link('product/product', 'product_id=' . (int)$this->request->post['product_id']), $product_info['name'], $this->url->link(self::ROUTE));
				$json['total'] = sprintf($this->language->get('new_text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

    /**
     * 删除收藏
     *
     * @throws Exception
     */
    public function remove()
    {
        if (! isset($this->request->post['product_id'])) {
            $this->responseJson([
                'code'  => ApiErrCode::REQUEST_PARAMS_EMPTY,
                'error' => 'product id required.'
            ]);

            return;
        }

        $this->load->language(self::ROUTE);

        $product_id = $this->request->post['product_id'];

        if ($this->customer->isLogged()) {
            $accountList = $this->modelAccountList();

            $accountList->deleteWishlist($product_id);
            $total_num = $this->modelAccountList()->getTotalWishlist();
            $total = sprintf($this->language->get('new_text_wishlist'), $total_num);
        } else if (isset($this->session->data['wishlist'])) {
            $del_index = array_search($product_id, $this->session->data['wishlist']);
            if ($del_index !== false) {
                array_splice($this->session->data['wishlist'], $del_index, 1);
            }

            $total_num = count($this->session->data['wishlist']);
            $total = sprintf($this->language->get('new_text_wishlist'), $total_num);
        } else {
            $total_num = $this->language->get('new_text_wishlist');
            $total = 0;
        }

        $this->responseOK(['msg' => "product id:[$product_id] deleted in wishlist."] + compact('total','total_num'));
    }

    /**
     * @return Model|ModelAccountWishlist
     * @throws Exception
     */
    public function modelAccountList()
    {
        return $this->loadModel(self::ROUTE);
    }
}
